package org.kiwi.util;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/7/28.
 */
public class MD5Util {

    private static MessageDigest md5Digest;

    static {
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {

        }
    }

    public static String getMd5ByFile(File file) throws Exception {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);

            MappedByteBuffer byteBuffer = fileInputStream.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            md5Digest.update(byteBuffer);

            return new BigInteger(1, md5Digest.digest()).toString(16);
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }

}
